/*
 * MIT License
 *
 * Copyright (c) 2023 北京凯特伟业科技有限公司
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 */
package com.je.meta.rpc.variable;

import com.google.common.base.Strings;
import com.je.common.auth.impl.Department;
import com.je.common.auth.impl.RealOrganizationUser;
import com.je.common.auth.impl.account.Account;
import com.je.common.base.service.rpc.SystemVariableRpcService;
import com.je.common.base.util.DateUtils;
import com.je.common.base.util.SecurityUserHolder;
import com.je.meta.cache.variable.BackCache;
import com.je.meta.cache.variable.FrontCache;
import com.je.meta.service.variable.MetaSysVariablesService;
import org.apache.servicecomb.provider.pojo.RpcSchema;
import org.springframework.beans.factory.annotation.Autowired;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.Optional;

@RpcSchema(schemaId = "systemVariableRpcService")
public class SystemVariableRpcServiceImpl implements SystemVariableRpcService {

    @Autowired
    public FrontCache frontCache;
    @Autowired
    public BackCache backCache;

    @Autowired
    private MetaSysVariablesService sysVariablesService;

    @Override
    public void reload() {
        sysVariablesService.reloadSystemVariables();
    }

    @Override
    public void writeBackVariable(String key, String value) {
        sysVariablesService.writeBackVariable(key,value);
    }

    @Override
    public String requireBackVariable(String key) {
        return sysVariablesService.findNativeBackVariable(key);
    }

    @Override
    public void writeFrontVariable(String key, String value) {
        sysVariablesService.writeFrontVariable(key,value);
    }

    @Override
    public String requireFrontVariable(String key) {
        return sysVariablesService.findNativeFrontVariable(key);
    }

    @Override
    public String requireSystemVariable(String key) {
        return sysVariablesService.findNativeSystemVariable(key);
    }

    @Override
    public Map<String, Object> systemVariables() {
        Map<String, Object> variables = new HashMap<>(64);

        //------- 用户基础信息
        RealOrganizationUser realOrganizationUser = SecurityUserHolder.getCurrentAccountRealUser();
        if(realOrganizationUser != null){
            variables.put("@USER_ID@", realOrganizationUser.getId());
            variables.put("@JE.currentUser.userId@", realOrganizationUser.getId());
            variables.put("@USER_CODE@", realOrganizationUser.getCode());
            variables.put("@JE.currentUser.userCode@", realOrganizationUser.getCode());
            variables.put("@USER_NAME@", realOrganizationUser.getName());
            variables.put("@JE.currentUser.username@", realOrganizationUser.getName());
        }

        Account account = SecurityUserHolder.getCurrentAccount();
        if(account != null){
            variables.put("@USER_DEPTMENT_USER_ID@", account.getDeptId());
            variables.put("@USER_ROLEIDS@", account.getRoleIds());
            variables.put("@JE.currentUser.roleIds@", account.getRoleIds());
            variables.put("@USER_ROLECODES@", account.getRoleCodes());
            variables.put("@JE.currentUser.roleCodes@", account.getRoleCodes());
            variables.put("@USER_ROLENAMES@", account.getRoleNames());
            variables.put("@JE.currentUser.roleNames@", account.getRoleNames());
            variables.put("@USER_PHONE@", account.getPhone());
            variables.put("@JE.currentUser.phone@", account.getPhone());
            variables.put("@USER_IDCARD@", account.getCardNum());
            variables.put("@JE.currentUser.idCard@", account.getCardNum());

            variables.put("@USER_TENANT_ID@", account.getTenantId());
            variables.put("@JE.currentUser.tenantId@", account.getTenantId());
            variables.put("@USER_TENANT_NAME@", account.getTenantName());
            variables.put("@JE.currentUser.tenantName@", account.getTenantName());
        }

        Department department = SecurityUserHolder.getCurrentAccountDepartment();
        if(department != null){
            variables.put("@USER_GROUP_COMPANY_ID@", department.getGroupCompanyId());
            variables.put("@JE.currentUser.groupCompanyId@", department.getGroupCompanyId());
            variables.put("@USER_GROUP_COMPANY_NAME@", department.getGroupCompanyName());
            variables.put("@JE.currentUser.groupCompanyName@", department.getGroupCompanyName());
            variables.put("@DEPT_ID@", department.getId());
            variables.put("@JE.currentUser.deptId@", department.getId());
            variables.put("@DEPT_CODE@", department.getCode());
            variables.put("@JE.currentUser.deptCode@", department.getCode());
            variables.put("@DEPT_NAME@", department.getName());
            variables.put("@JE.currentUser.deptName@", department.getName());
            variables.put("@DEPT_PARENT_ID@", department.getParent());
            variables.put("@JE.currentUser.dept.parentId@", department.getParent());
        }
        //------- 时间变量
        variables.put("@NOW_DATE@", DateUtils.formatDate(new Date()));
        variables.put("@NOW_MONTH@", DateUtils.formatDate(new Date(), "yyyy-MM"));
        variables.put("@NOW_TIME@", DateUtils.formatDateTime(new Date()));
        variables.put("@NOW_YEAR@", DateUtils.formatDate(new Date(), "yyyy"));
        variables.put("@NOW_ONLYMONTH@", DateUtils.formatDate(new Date(), "MM"));

        String currentTenantId = SecurityUserHolder.getCurrentAccountTenantId();
        if(Strings.isNullOrEmpty(currentTenantId)){
            //添加前台变量
            Map<String, String> frontVar = frontCache.getCacheValues();
            Optional.ofNullable(frontVar).ifPresent(variables::putAll);
            //添加后台变量
            Map<String, String> backVar = backCache.getCacheValues();
            Optional.ofNullable(backVar).ifPresent(variables::putAll);
        }else {
            //添加前台变量
            Map<String, String> frontVar = frontCache.getCacheValues(currentTenantId);
            Optional.ofNullable(frontVar).ifPresent(variables::putAll);
            //添加后台变量
            Map<String, String> backVar = backCache.getCacheValues(currentTenantId);
            Optional.ofNullable(backVar).ifPresent(variables::putAll);
        }
        return variables;
    }

    @Override
    public Map<String, Object> formatCurrentUserAndCachedVariables() {
        Map<String, Object> ddMap = new HashMap<>();
        //加入登录信息
        ddMap.putAll(SecurityUserHolder.getCurrentInfo());
        String currentTenantId = SecurityUserHolder.getCurrentAccountTenantId();
        if(Strings.isNullOrEmpty(currentTenantId)){
            //加入用户变量
            ddMap.putAll(frontCache.getCacheValues());
            ddMap.putAll(backCache.getCacheValues());
        }else {
            //加入用户变量
            ddMap.putAll(frontCache.getCacheValues(currentTenantId));
            ddMap.putAll(backCache.getCacheValues(currentTenantId));
        }
        return ddMap;
    }

}
